/* global React */
// This Week — active round command center for the league.
function DashboardScreen({ setTab }) {
  const { StandingRow, Card, Button, Badge } = window.GT7LeagueDesignSystem_258437;
  const D = window.GT7DATA;
  const next = D.schedule.find(r => r.status === 'next') || D.schedule[D.schedule.length - 1];
  const leaders = D.drivers.slice(0, 4);
  const poll = D.poll;
  const totalVotes = poll.options.reduce((a, o) => a + o.votes, 0);
  const leadOpt = [...poll.options].sort((a, b) => b.votes - a.votes)[0];
  const voteTarget = D.drivers.length || 6;
  const missingVotes = Math.max(0, voteTarget - totalVotes);
  const [, tick] = React.useState(0);
  React.useEffect(() => { const h = () => tick(t => t + 1); window.addEventListener('gt7-vote', h); return () => window.removeEventListener('gt7-vote', h); }, []);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div className="race-command-panel" style={{
        position: 'relative', overflow: 'hidden',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--border-subtle)',
        background: 'linear-gradient(120deg, var(--ink-850) 0%, var(--ink-900) 58%, var(--ink-950) 100%)',
        boxShadow: 'var(--shadow-md)',
      }}>
        <span style={{ position: 'absolute', top: 0, right: 0, width: 5, height: '100%', background: 'var(--brand)', boxShadow: 'var(--glow-brand)' }} />
        <TrackMapMark />

        <div style={{ position: 'relative', padding: '24px 28px 18px' }}>
          <RaceControlStrip next={next} poll={poll} totalVotes={totalVotes} voteTarget={voteTarget} />

          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', gap: 24, alignItems: 'end', marginTop: 22 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 10 }}>
                <Badge tone="pole">Round {next.round}</Badge>
                <Badge tone="danger">Voting open</Badge>
                {next.fromVote && <Badge tone="positive">Set by vote</Badge>}
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-faint)' }}>{D.meta.raceDay} {D.meta.raceTime} · lobby {D.meta.lobby}</span>
              </div>
              <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 48, lineHeight: .96, color: 'var(--text-strong)', letterSpacing: 0, textTransform: 'uppercase' }}>{next.track}</h1>
              <div className="race-fact-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 16, marginTop: 18, maxWidth: 860 }}>
                <RaceFact label="Sprint pool" value={next.sprint} />
                <RaceFact label="Feature car" value={next.featureCar} />
                <RaceFact label="Feature length" value={`${next.laps} laps · ~28 min`} mono />
              </div>
            </div>

            <div className="race-actions" style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 150 }}>
              <Button variant="primary" onClick={() => setTab('Vote')}>Cast vote</Button>
              <Button variant="secondary" onClick={() => setTab('Results')}>Enter results</Button>
            </div>
          </div>
        </div>

        <div className="race-status-grid" style={{
          position: 'relative',
          display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
          borderTop: '1px solid var(--border-subtle)',
          background: 'rgba(5,7,10,.36)',
        }}>
          <StatusMetric label="Poll leader" value={leadOpt.title} tone="cyan" />
          <StatusMetric label="Votes recorded" value={`${totalVotes}/${voteTarget}`} detail={missingVotes ? `${missingVotes} missing` : 'grid complete'} tone={missingVotes ? 'amber' : 'green'} />
          <StatusMetric label="Championship leader" value={D.drivers[0].name} detail={`${D.drivers[0].points} pts`} tone="gold" />
          <StatusMetric label="Next action" value="Vote before lock" detail={poll.closes} tone="brand" />
        </div>
      </div>

      <div className="race-week-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.45fr) minmax(320px, .85fr)', gap: 20, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <section>
            <SectionHead title="Active ballot" action="Open voting" onAction={() => setTab('Vote')} />
            <div style={{ display: 'grid', gap: 10 }}>
              {poll.options.slice(0, 4).map((option, index) => (
                <ProposalRow key={option.id} option={option} index={index} totalVotes={totalVotes} leading={option.id === leadOpt.id} />
              ))}
            </div>
          </section>

          <section>
            <SectionHead title="Round settings" action="Season view" onAction={() => setTab('Season')} />
            <Card>
              <div className="race-settings-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 14 }}>
                <SettingTile label="Race 1" value="5-lap sprint" detail="No wear · no fuel · no damage" />
                <SettingTile label="Race 2" value="Feature by laps" detail="Wear, fuel, light damage" />
                <SettingTile label="Draft" value="Real" detail="Boost off · BoP as listed" />
                <SettingTile label="Nitrous" value="Prohibited" detail="Qualifying ≤ 12 min" />
              </div>
            </Card>
          </section>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <section>
            <SectionHead title="Timing tower" action="Full table" onAction={() => setTab('Standings')} />
            <Card padded={false}>
              {leaders.map((d, i) => (
                <StandingRow key={d.number} position={i + 1} number={d.number} name={d.name}
                  points={d.points} delta={i === 0 ? null : d.points - leaders[0].points}
                  poles={d.poles} fastestLaps={d.fl} leader={i === 0} />
              ))}
            </Card>
          </section>

          <section>
            <SectionHead title="Last round" action="Enter results" onAction={() => setTab('Results')} />
            <Card accent="cyan">
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start' }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Round {D.lastRound.round}</div>
                  <div style={{ marginTop: 5, fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>{D.lastRound.track}</div>
                </div>
                <Badge tone="caution">Results pending</Badge>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 16 }}>
                <MiniImpact label="Winner" value={D.drivers[0].name} />
                <MiniImpact label="Big move" value={`+${D.drivers[0].points - D.drivers[1].points}`} />
                <MiniImpact label="Fastest" value={D.drivers.find(d => d.fl > 1)?.name || D.drivers[0].name} />
              </div>
            </Card>
          </section>
        </div>
      </div>
    </div>
  );
}

function RaceControlStrip({ next, poll, totalVotes, voteTarget }) {
  return (
    <div className="race-control-strip" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(0, 1fr))', gap: 1, border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', overflow: 'hidden', background: 'var(--border-subtle)' }}>
      <ControlCell label="Race control" value="Voting open" tone="brand" />
      <ControlCell label="Round" value={`R${next.round}`} />
      <ControlCell label="Vote close" value={poll.closes.replace(' · 6 drivers', '')} />
      <ControlCell label="Ballots" value={`${totalVotes}/${voteTarget}`} tone={totalVotes >= voteTarget ? 'green' : 'amber'} />
      <ControlCell label="State" value={next.fromVote ? 'Track set' : 'Track fluid'} tone={next.fromVote ? 'green' : 'cyan'} />
    </div>
  );
}

function ControlCell({ label, value, tone }) {
  const colors = { brand: 'var(--brand)', cyan: 'var(--accent)', green: 'var(--green-500)', amber: 'var(--amber-500)' };
  return (
    <div style={{ minWidth: 0, padding: '9px 11px', background: 'rgba(15,19,26,.88)', borderTop: `2px solid ${colors[tone] || 'transparent'}` }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{label}</div>
      <div style={{ marginTop: 3, fontFamily: 'var(--font-mono)', fontSize: 12, color: colors[tone] || 'var(--text-body)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
    </div>
  );
}

function RaceFact({ label, value, mono }) {
  return (
    <div style={{ minWidth: 0 }}>
      <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{label}</span>
      <span style={{ display: 'block', marginTop: 5, fontFamily: mono ? 'var(--font-mono)' : 'var(--font-body)', fontSize: 14, color: 'var(--text-body)', lineHeight: 1.35 }}>{value}</span>
    </div>
  );
}

function StatusMetric({ label, value, detail, tone }) {
  const colors = { brand: 'var(--brand)', cyan: 'var(--accent)', green: 'var(--green-500)', amber: 'var(--amber-500)', gold: 'var(--gold-500)' };
  return (
    <div style={{ minWidth: 0, padding: '15px 18px', borderRight: '1px solid var(--border-subtle)' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{label}</div>
      <div style={{ marginTop: 5, fontFamily: 'var(--font-display)', fontSize: 18, lineHeight: 1.1, fontWeight: 700, color: colors[tone] || 'var(--text-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
      {detail && <div style={{ marginTop: 4, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-faint)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{detail}</div>}
    </div>
  );
}

function ProposalRow({ option, index, totalVotes, leading }) {
  const pct = totalVotes ? Math.round((option.votes / totalVotes) * 100) : 0;
  const tone = leading ? 'var(--accent)' : index === 1 ? 'var(--ink-400)' : 'var(--ink-600)';
  return (
    <div style={{
      position: 'relative',
      padding: '14px 16px',
      background: leading ? 'rgba(23,198,232,.07)' : 'var(--surface-card)',
      border: `1px solid ${leading ? 'rgba(23,198,232,.65)' : 'var(--border-subtle)'}`,
      borderLeft: `3px solid ${tone}`,
      borderRadius: 'var(--radius-md)',
      overflow: 'hidden',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'start', position: 'relative' }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            {leading && <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--accent)' }}>Leader</span>}
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, color: 'var(--text-strong)', lineHeight: 1.2 }}>{option.title}</span>
          </div>
          <div style={{ marginTop: 5, fontSize: 12.5, color: 'var(--text-faint)', lineHeight: 1.35 }}>{option.meta}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, lineHeight: 1, fontWeight: 700, color: tone }}>{option.votes}</div>
          <div style={{ marginTop: 2, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-faint)' }}>{pct}%</div>
        </div>
      </div>
      <div style={{ height: 5, background: 'var(--ink-800)', borderRadius: 999, overflow: 'hidden', marginTop: 12 }}>
        <div style={{ height: '100%', width: `${pct}%`, background: tone, borderRadius: 999 }} />
      </div>
    </div>
  );
}

function SettingTile({ label, value, detail }) {
  return (
    <div style={{ minWidth: 0, padding: '12px 13px', background: 'var(--ink-900)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{label}</div>
      <div style={{ marginTop: 6, fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, color: 'var(--text-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
      <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-faint)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{detail}</div>
    </div>
  );
}

function MiniImpact({ label, value }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{label}</div>
      <div style={{ marginTop: 5, fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, color: 'var(--text-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
    </div>
  );
}

function TrackMapMark() {
  return (
    <svg aria-hidden="true" viewBox="0 0 360 220" style={{ position: 'absolute', right: 70, top: 18, width: 330, height: 210, opacity: .12, pointerEvents: 'none' }}>
      <path d="M72 128c-26-6-41-23-38-47 4-35 41-52 78-36 22 10 33 28 54 31 37 5 41-42 81-39 34 3 63 32 60 67-3 34-30 58-68 61-36 3-57-15-82-14-31 2-48 24-85 15-28-7-40-22-36-36 3-10 15-12 36-2Z" fill="none" stroke="var(--accent)" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M85 133c21 3 39-9 59-15 31-9 52 11 80 5 20-4 34-18 35-37" fill="none" stroke="var(--brand)" strokeWidth="5" strokeLinecap="round" />
    </svg>
  );
}

function SectionHead({ title, action, onAction }) {
  const { Button } = window.GT7LeagueDesignSystem_258437;
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
      <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{title}</h2>
      {action && <Button variant="ghost" size="sm" onClick={onAction}>{action}</Button>}
    </div>
  );
}
window.DashboardScreen = DashboardScreen;
window.SectionHead = SectionHead;
